<?php

namespace App\Services;

class PHPWordService extends BasicService
{
    public static function genWordByTemplates(string $templateFile, array $vars)
    {
        $ext = pathinfo($templateFile, PATHINFO_EXTENSION);
        if (!in_array($ext, ['docx'])) {
            return self::error('格式不支持,仅支持docx文件模板');
        }
        if (!file_exists($templateFile)) {
            return self::error('文件不存在');
        }
        $loadTemplate = new \PhpOffice\PhpWord\TemplateProcessor($templateFile);
        foreach ($vars as $field => $val) {
            $loadTemplate->setValue($field, $val);
        }

        $saveName = uniqid() . pathinfo($templateFile, PATHINFO_EXTENSION);

        $loadTemplate->saveAs($saveName);
        if (file_exists($saveName)) {
            return self::success(['file_path' => $saveName]);
        } else {
            return self::error('生成文件失败');
        }
    }
}
